import { IDeviceCategory, IResponse } from '@/interfaces/common.interface';
import { Button, Cell, DropdownItem, DropdownMenu, Field, Icon } from 'vant';
import { Component, Vue } from 'vue-property-decorator';
import style from '../styles/device.module.less';

interface LoRaDeviceInfo {
  alias: string; // LoRa device alias.
  devEUI: string; // LoRa device EUI.
}

@Component({
  components: {
    'van-button': Button,
    'van-field': Field,
    'van-dropdown-menu': DropdownMenu,
    'van-dropdown-item': DropdownItem,
    'van-cell': Cell,
    'van-icon': Icon
  },
  sockets: {
    connect() {
      // 获取最新的设备列表
      this.$socket &&
        this.$socket.client.emit('list', 'lora', (res: IResponse) => {
          if (res && res.result) {
            this.$data.list = res.data;
          }
        });
    },

    list(data: { type: IDeviceCategory; data: LoRaDeviceInfo[] }) {
      if (data.type === 'lora' && Array.isArray(data.data)) {
        this.$data.list = data.data;
      }
    },

    message(data: { type: IDeviceCategory; devEUI: string; data: string }) {
      console.log('message: ', data);
      if (
        data.type === 'lora' &&
        data.devEUI &&
        this.$data.selectedDev &&
        data.devEUI === this.$data.selectedDev.devEUI
      ) {
        this.$data.receiveMessage = data.data;
      }
    }
  }
})
export default class Lora extends Vue {
  private sendMessage = '';
  private receiveMessage = '';
  private selectedDev: LoRaDeviceInfo | null = null;
  private list: LoRaDeviceInfo[] = [];

  private get hasLoraPermission() {
    return this.$store.state.permissions && this.$store.state.permissions.lora;
  }

  public created() {
    this.$socket &&
      this.$socket.client.emit('list', 'lora', (res: IResponse) => {
        if (res && res.result) {
          this.list = res.data;
        }
      });
  }

  public render() {
    return (
      <div class={style['device-message']}>
        <p class={style['device-message-title']}>【通信设备】：</p>
        <van-dropdown-menu class={style['device-message-dropdown']} active-color='#20a5de'>
          <van-dropdown-item title={(this.selectedDev && this.selectedDev.alias) || ''} ref='dropdown'>
            {this.list.map((item: LoRaDeviceInfo) => (
              <van-cell
                center
                title={item.alias}
                on-click={() => {
                  this.handleChange(item);
                }}>
                {this.selectedDev && this.selectedDev.devEUI === item.devEUI && (
                  <van-icon name='success' slot='right-icon' color='#07c160' />
                )}
              </van-cell>
            ))}
          </van-dropdown-item>
        </van-dropdown-menu>

        <div class={style['device-message-content']}>
          <p class={style['device-message-title']}>【发送数据】：</p>
          <div class={style['device-message-send']}>
            <van-field v-model={this.sendMessage} rows='3' autosize type='textarea' placeholder='请输入要发送的消息' />
          </div>

          <div class={style['device-message-btn']}>
            <van-button
              size='small'
              on-click={this.submitMessage}
              disabled={!this.selectedDev}
              plain
              hairline
              color='#20a5de'>
              send
            </van-button>
          </div>

          <p class={style['device-message-title']}>【响应数据】：</p>
          <div>
            <van-field
              value={this.receiveMessage}
              readonly
              rows='3'
              autosize
              type='textarea'
              placeholder='接收当前选中设备的消息'
            />
          </div>
        </div>

        {/* 权限判断 */}
        {!this.hasLoraPermission && (
          <div class={style['permission']}>
            <p>
              当前模块需要开启<span>{` LoRa权限 `}</span>，请按照以下路径进行手动配置：
            </p>
            <span>{`设置 > 隐私设置 > 应用权限 > LoRa通信 > 系统权限`}</span>
          </div>
        )}

        {/* 权限判断 */}

        <div class={style['permission']}>
          <p>
            Lora模块当前无法使用！
          </p>
        </div>
      </div>
    );
  }

  /* 切换选中设备 */
  private handleChange(v: LoRaDeviceInfo) {
    this.selectedDev = v;
    this.sendMessage = '';
    this.receiveMessage = '';
    (this.$refs.dropdown as any).toggle();
  }

  /* 发送设备消息 */
  private submitMessage() {
    if (!this.selectedDev) {
      return this.$edger.notify.warning('未选择设备！');
    }
    if (!this.sendMessage) {
      return this.$edger.notify.warning('待发送内容不可为空！');
    }
    this.$socket.client.emit(
      'send-message',
      { type: 'lora', data: { devEUI: this.selectedDev?.devEUI, data: this.sendMessage } },
      (res: any) => {
        if (!res || !res.result) {
          this.$edger.notify.error(res.message || '操作失败！');
        }
      }
    );
  }
}
